package com.kintreda.ieco_server.module.account.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import com.kintreda.ieco_server.bean.account.Menu;
import com.kintreda.ieco_server.bean.account.Role;
import com.kintreda.ieco_server.bean.account.User;
import com.kintreda.ieco_server.core.repository.IBaseRepository;
import com.kintreda.ieco_server.core.service.impl.BaseServiceImpl;
import com.kintreda.ieco_server.module.account.service.IMenuService;
import com.kintreda.ieco_server.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 菜单信息管理service
 * @author HuangZhongYao
 *
 */
@Service("menuService")
public class MenuServiceImpl extends BaseServiceImpl<Menu, String> implements IMenuService {
	
	@Autowired
	private IBaseRepository<Menu, String> baseRepository;
	
	/*********************************************************
	 * 获取授权给用户的菜单信息列表
	 * @param user
	 * @return
	 */
	@Override
	public List<Menu> getMenuByUserId(User user) {
		
		Set<Role> roles = user.getRoles();
		List<String> rids = new ArrayList<String>();
		for (Role role : roles) {
			rids.add(role.getId());
		}
		
		if(Assert.notEmpty(rids)) {
			String hql = "select distinct c from Menu c join c.roles role where role.id in(:rids) order by c.pid,orderNum asc";
			return this.findByNamedParam(hql, "rids", rids);
		} else {
			return null;
		}
		
	}

	/*********************************************************
	 * 获取所有的菜单新列表
	 * @return
	 */
	@Override
	public List<Menu> getAll() {
		return super.query(" from Menu order by orderNum asc", null);
	}

	@Override
	public List<Menu> getAllMenu() {
		return super.query(" from Menu where menuButton='menu' order by orderNum asc", null);
	}

	@Override
	public List<Menu> getMenuByPid(String string) {
		return super.query(" from Menu where pid='"+string+"'",null);
	}
	
	
	/*********************************************************
	 * 添加查询菜单信息列表
	 * @param menu
	 * @return
	 */
	public List<Menu> findMenuList(Menu menu) {

		StringBuffer hql = new StringBuffer(" select t from Menu t where t.status=1");
		List<Object> valueList = new ArrayList<Object>();
		if(menu != null) {
			if(Assert.hasText(menu.getPid())) {
				hql.append(" and t.pid=?");
				valueList.add(menu.getPid());
			}
			
			if(Assert.hasText(menu.getUrl())) {
				hql.append(" and t.url<>?");
				valueList.add(menu.getUrl());
			}
		}
		
		hql.append(" order by t.id desc");
		
		return this.baseRepository.findList(hql.toString(), valueList.toArray());
	}
}
